package com.qf.homework.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.homework.entity.Ticket;
import com.qf.homework.entity.Vote;
import com.qf.homework.service.TicketService;
import com.qf.homework.service.VoteService;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
@ServerEndpoint("/webSocket")
public class WebSocketServer implements ApplicationContextAware {


    private static ConcurrentHashMap<String,Session> sessionMap = new ConcurrentHashMap<>();

    /**前端发送请求建立websocket连接，就会执行@OnOpen方法**/
    @OnOpen
    public void open(Session session){
        System.out.println(session.getId()+"连接成功");
        sessionMap.put(session.getId(),session);
    }
    /**前端关闭页面或者主动关闭websocket连接，都会执行close**/
    @OnClose
    public void close(Session session){
        System.out.println(session.getId()+"连接断开了------------");
        sessionMap.remove(session.getId());
    }

    public static void sendMsg(String sessionId,String msg){
        try {
            Session session = sessionMap.get(sessionId);
            session.getBasicRemote().sendText(msg);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Scheduled(cron = "0/3 * * * * ?")
    public void printHelloWorld(){
//        VoteService voteService = (VoteService) TaskUtil.getBean("voteServiceImpl");

        VoteService voteService = (VoteService)getBean("voteServiceImpl");

        String nums = voteService.selectCountPeople();

        for (Map.Entry<String, Session> stringSessionEntry : sessionMap.entrySet()) {
            sendMsg(stringSessionEntry.getKey(),""+nums);
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context=applicationContext;
    }
    private static ApplicationContext context;
    public static ApplicationContext getApplicationContext() {return context;}
    public static Object getBean(String name) { return getApplicationContext().getBean(name); }
}